﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WareHouse.Repositories;
using WareHouse.Domain.ModelClass;
using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using Panda.DynamicWebApi;
using System.Runtime.CompilerServices;
using Panda.DynamicWebApi.Attributes;
using Microsoft.AspNetCore.Authorization;
using SqlSugar;
using WareHose.Application.ProductAll.Dto;
using WareHose.Application.Admins.Dto;
using WareHouse.Domain;
using System.Text.RegularExpressions;
using Mysqlx.Crud;

namespace WareHose.Application.ProductAll
{
    /// <summary>
    /// 产品管理
    /// </summary>
    [DynamicWebApi]
    [ApiExplorerSettings(GroupName ="v1")]
    [Authorize]
    public class ProductService : IProductService,IDynamicWebApi
    {
        private readonly IBaseRepository<ProductInfo> baseRepository;
        private readonly IBaseRepository<ProductType> productTypeRepository;
        private readonly ISqlSugarClient sugarClient;
        private readonly IMapper mapper;
        public ProductService(IBaseRepository<ProductInfo> baseRepository, IBaseRepository<ProductType> productTypeRepository, IMapper mapper, ISqlSugarClient sugarClient)
        {
            this.baseRepository = baseRepository;
            this.productTypeRepository = productTypeRepository;
            this.mapper = mapper;
            this.sugarClient = sugarClient;
        }
        /// <summary>
        /// 产品类型添加
        /// </summary>
        /// <param name="productType"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<ResultDto> AddProductType(ProductType productType)
        {
            try
            {
                await productTypeRepository.InsertAsync(productType);
                return new ResultDto
                {
                    Code = Status.Success,
                    Message = "产品类别添加成功！"
                };
            }
            catch (Exception e)
            {
                return new ResultDto { Code = Status.Failed, Message = e.Message };

            }


        }
        /// <summary>
        /// 产品类型显示
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<ResultDto<List<ProductType>>> ShowProductType()
        {
            try
            {
                //第三个参数为0 表示 ： parentid为 0 设置成根目录, 正常情况下最顶层的parentid不是0就是null
                var tree = sugarClient.Queryable<ProductType>().ToTree(it => it.Child, it => it.Pid, 0);
              
                return new ResultDto<List<ProductType>>
                {
                    Code = Status.Success,
                    Data= tree
                };
            }
            catch (Exception e)
            {
                return new ResultDto<List<ProductType>>
                {
                    Code = Status.Success,
                    Message = e.Message
                };
                throw;
            }
        }
        /// <summary>
        /// 产品修改
        /// </summary>
        /// <returns></returns>
        [HttpPut]
        [AllowAnonymous]
        public async Task<ResultDto> UpdProductType(ProductType productType)
        {
            try
            {
                var res = await productTypeRepository.FistAsync(x => x.ProductTypeId != productType.ProductTypeId && x.ProductTypeName == productType.ProductTypeName);
                if (res == null)
                {
                    await productTypeRepository.UpdateAsync(productType);
                    return new ResultDto
                    {
                        Code = Status.Success,
                        Message = "产品信息修改成功！"
                    };
                }
                else
                {
                    return new ResultDto
                    {
                        Code = Status.Success,
                        Message = "产品信息修改失败！"

                    };
                }
            }
            catch (Exception e)
            {
                return new ResultDto
                {
                    Code = Status.Success,
                    Message = e.Message
                };
                throw;
            }
        }
        /// <summary>
        /// 返回查询到的单条产品信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<ResultDto<ProductType>> BackProudtcType(string id)
        {
            try
            {
                var res = await productTypeRepository.FistAsync(x => x.ProductTypeId.ToString().Contains(id));
                return new ResultDto<ProductType>
                {
                    Code = Status.Success,
                    Data = res
                };
            }
            catch (Exception e)
            {
                return new ResultDto<ProductType>
                {
                    Code = Status.Success,
                    Message = e.Message
                };
                throw;
            }
        }
        /// <summary>
        /// 产品删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete]
        [AllowAnonymous]
        public async Task<ResultDto<bool>> DeleteTypeAsync(long id)
        {
            try
            {

                var result = await productTypeRepository.Delete(id);
                if (result > 0)
                {
                    return new ResultDto<bool>
                    {
                        Code = Status.Success,
                        Data = true,
                        Message = "删除成功！"
                    };
                }
                else
                {
                    return new ResultDto<bool>
                    {
                        Code = Status.Failed,
                        Data = false,
                        Message = "删除失败"
                    };
                }
            }
            catch (Exception e)
            {
                return new ResultDto<bool>
                {
                    Code = Status.Failed,
                    Message = e.Message
                };
                throw;
            }
        }
        /// <summary>
        /// 产品添加
        /// </summary>
        /// <param name="productInfo"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<ResultDto> AddProduct(ProductInfo productInfo)
        {
            try
            {

                if (await baseRepository.FistAsync(x => x.ProductName == productInfo.ProductName)==null)
                {
                    if(await baseRepository.InsertAsync(productInfo) != 0)
                    {
                        return new ResultDto { Code = Status.Success, Message = "添加成功" };
                    }
                    else
                    {
                        return new ResultDto { Code = Status.Success, Message = "添加失败" };
                    }
                    
                }
                else
                {
                    return new ResultDto { Code = Status.Success, Message = "此产品已存在" };
                }


            }
            catch (Exception e)
            {

                return new ResultDto { Code = Status.Failed, Message = e.Message };
            }
        }
        /// <summary>
        /// 产品条件分页显示
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<ResultDto<PagingDto<ProductOut>>> ShowProduct(long ProductTypeId, string ProductName,int Type,int pageindex=1,int pagesize=10)
        {
            try
            {

                //联表查询
                var query5 = sugarClient.Queryable<ProductInfo, ProductType>((a, b) => new JoinQueryInfos(JoinType.Left, a.ProductTypeId == b.ProductTypeId))
                         .Select((a, b) => new ProductOut
                         {
                             ProductId = a.ProductId.ToString(),
                             ProductName = a.ProductName,
                             ProductTypeName = b.ProductTypeName,
                             FacturerCode = a.FacturerCode,
                             Specification = a.Specification,
                             Unit = a.Unit,
                             MinWarn = a.MinWarn,
                             MaxWarn = a.MaxWarn,
                             PackType = a.PackType,
                             Price = a.Price,
                             Weight = a.Weight,
                             Supplier = a.Supplier
                         })
                         .WhereIF(ProductTypeId != 0, a => a.ProductTypeId == ProductTypeId)
                        .WhereIF(!string.IsNullOrEmpty(ProductName), a => a.ProductName.Contains(ProductName))
                         .WhereIF((Type != 0), a => a.Supplier == (SupplierType)Type).ToList();





                //条件从那个表中获取
                var exp = Expressionable.Create<ProductInfo>();
                
                
                //分页
                var page =await baseRepository.PageAsync(pageindex,pagesize, exp.ToExpression());
                
                //总页数
                var totalPage = (int)Math.Ceiling((double)page.Item1 / pagesize);
                return new ResultDto<PagingDto<ProductOut>>
                {
                    Code = Status.Success,
                    Message = "成功",
                    Data = new PagingDto<ProductOut>
                    {
                        TotalRows = query5.Count,
                        Rows = query5,
                        TotalPage = totalPage,
                    }
                };
            }
            catch (Exception e)
            {
                return new ResultDto<PagingDto<ProductOut>>
                {
                    Code = Status.Failed,
                    Message =e.Message,
                };
                throw;
            }
        }
       
        /// <summary>
        /// 产品修改
        /// </summary>
        /// <returns></returns>
        [HttpPut]
        [AllowAnonymous]
        public async Task<ResultDto> UpdProduct(ProductInfo productInfo)
        {  
            try
            {
                var res = await baseRepository.FistAsync(x => x.ProductId!=productInfo.ProductId && x.ProductName==productInfo.ProductName );
                if (res == null)
                {
                    await baseRepository.UpdateAsync(productInfo);
                    return new ResultDto
                    {
                        Code = Status.Success,
                        Message = "产品信息修改成功！"
                    };
                }
                else
                {
                    return new ResultDto
                    {
                        Code = Status.Success,
                        Message = "产品信息修改失败！"

                    };
                }
            }
            catch (Exception e)  
            {
                return new ResultDto
                {
                    Code = Status.Success,
                    Message = e.Message
                };
                throw;
            }
        }
        /// <summary>
        /// 返回查询到的单条产品信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<ResultDto<ProductInfo>> BackProudtc(string id)
        {
            try
            {
                var res = await baseRepository.FistAsync(x => x.ProductId.ToString().Contains(id));
                return new ResultDto<ProductInfo>
                {
                    Code = Status.Success,
                    Data= res
                };
            }
            catch (Exception e)
            {
                return new ResultDto<ProductInfo>
                {
                    Code = Status.Success,
                    Message = e.Message
                };
                throw;
            }
        }
        /// <summary>
        /// 产品删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete]
        [AllowAnonymous]
        public async Task<ResultDto> DeleteAsync(string id)
        {
            try
            {
                if (id != null)
                {
                    string[] ids = id.Split(',');
                    foreach (var item in ids)
                    {
                        await baseRepository.Delete(Convert.ToInt64(item));
                    }
                    return new ResultDto { Code = Status.Success, Message = "删除成功" };
                }
                else
                {
                    return new ResultDto { Code = Status.Success, Message = "删除失败" };
                }
            }
            catch (Exception e)
            {
                return new ResultDto<bool>
                {
                    Code = Status.Failed,
                   Message = e.Message
                };
                throw;
            }
        }
        
    }
}
